import { uploadApi } from "@/api/common";
import { message } from "ant-design-vue";
import { Ref } from "vue";

export default function InitHook(state: {
  emit: any;
  value: Ref<any>;
  valueType: Ref<string>;
  mode: Ref<string>;
  pastId: Ref<string>;
  maxCount: Ref<number>;
  fileList: Ref<Array<Base.GeneraDataType>>;
}) {
  const { pastId, fileList, maxCount, mode, valueType, value, emit } = state;
  const initPastImg = () => {
    const pastDom = document.getElementById(pastId.value);
    const pastTipDom = document.querySelector(".past-wrapper > .past-tip");
    if (pastTipDom) {
      pastTipDom.addEventListener("click", () => {
        pastDom?.focus();
      });
      pastDom?.addEventListener("paste", (e: any) => {
        if (maxCount.value <= fileList.value.length) return message.error(`最多上传${maxCount.value}张图片!`);
        const items = (e.clipboardData || window.Clipboard).files;
        if (items && items.length) {
          const fromData = new FormData();
          fromData.append("file", items[0]);
          return uploadApi({ path: mode.value }, fromData).then((res: any) => {
            let result: Base.GeneraDataType[] = [];
            if (valueType.value === "2") result = value.value.concat(res.data);
            else result = value.value.concat(res.data.url);
            emit("update:value", result);
          });
        }
      });
      pastDom?.addEventListener("input", (e: any) => {
        e.target.textContent = null;
      });
    }
  };
  return {
    initPastImg
  };
}
